import type { Recordable } from '@/types/global'
import { dayjs } from 'element-plus'
import { intersectionWith, isArray, isEqual, isObject, mergeWith, unionWith } from 'lodash-es'
import AES from './ar-aes.js'

/**
 * Recursively merge two objects.
 * 递归合并两个对象。

 * @param source The source object to merge from. 要合并的源对象。
 * @param target The target object to merge into. 目标对象，合并后结果存放于此。
 * @param mergeArrays How to merge arrays. Default is "replace".
 *        如何合并数组。默认为replace。
 *        - "union": Union the arrays. 对数组执行并集操作。
 *        - "intersection": Intersect the arrays. 对数组执行交集操作。
 *        - "concat": Concatenate the arrays. 连接数组。
 *        - "replace": Replace the source array with the target array. 用目标数组替换源数组。
 * @returns The merged object. 合并后的对象。
 */
export function deepMerge<T extends null | object | undefined, U extends null | object | undefined>(
  source: T,
  target: U,
  mergeArrays: 'concat' | 'intersection' | 'replace' | 'union' = 'replace',
): T & U {
  if (!target) {
    return source as T & U
  }
  if (!source) {
    return target as T & U
  }
  return mergeWith({}, source, target, (sourceValue: any[] | string, targetValue: any) => {
    if (isArray(targetValue) && isArray(sourceValue)) {
      switch (mergeArrays) {
        case 'concat': {
          return [...(sourceValue as Array<T>), ...targetValue]
        }
        case 'intersection': {
          return intersectionWith(sourceValue, targetValue, isEqual)
        }
        case 'replace': {
          return targetValue
        }
        case 'union': {
          return unionWith(sourceValue, targetValue, isEqual)
        }
        default: {
          throw new Error(`Unknown merge array strategy: ${mergeArrays as string}`)
        }
      }
    }
    if (isObject(targetValue) && isObject(sourceValue)) {
      return deepMerge(sourceValue as object, targetValue, mergeArrays)
    }
    return undefined
  })
}
const hexList: string[] = []
for (let i = 0; i <= 15; i++) {
  hexList[i] = i.toString(16)
}
/**生成key */
export function buildUUID(): string {
  let uuid = ''
  for (let i = 1; i <= 36; i++) {
    if (i === 9 || i === 14 || i === 19 || i === 24) {
      uuid += '-'
    } else if (i === 15) {
      uuid += 4
    } else if (i === 20) {
      uuid += hexList[(Math.random() * 4) | 8]
    } else {
      uuid += hexList[(Math.random() * 16) | 0]
    }
  }
  return uuid.replace(/-/g, '')
}
// 对象中的key按照a-z排序 并且加密
export function objKeyAes(obj: Recordable): Recordable {
  let stringObj = dayjs().format('YYYY-MM') //要加密的字符串
  let newObj: any = {} //新 obj
  if (obj) {
    let newKey: any = Object.keys(obj).sort()
    for (let i = 0; i < newKey.length; i++) {
      newObj[newKey[i]] = obj[newKey[i]]
      stringObj += '&' + newKey[i]
    }
  }
  // console.log('stringObj', stringObj);
  // 文档地址 https://ext.dcloud.net.cn/plugin?id=4317
  let e = AES.encrypt(stringObj, '6787654321234567', '6787654321234567')
  return {
    ...newObj, //新 obj
    hash: e, // 加密后的字符串
  }
}
